import router, { asyncRoutes, constantRoutes } from "@/router";

function hasPermission(route, roles) {
  if (route.meta && route.meta.roles && route.meta.roles.length) {
    return roles.some(role => route.meta.roles.includes(role));
  } else {
    return true;
  }
}

function filterAccessRoutes(routes, roles) {
  let result = [];

  routes.forEach(route => {
    let tmpRoute = { ...route };
    if (hasPermission(tmpRoute, roles)) {
      if (tmpRoute.children && tmpRoute.children.length) {
        tmpRoute.children = filterAccessRoutes(tmpRoute.children, roles);
      }
      result.push(tmpRoute);
    }
  });

  return result;
}

const state = {
  routes: []
};

const mutations = {
  SET_ROUTES(state, routes) {
    state.routes = [...constantRoutes, ...routes];
    router.addRoutes(state.routes);
  }
};

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      let routes = filterAccessRoutes(asyncRoutes, roles);

      commit("SET_ROUTES", routes);

      resolve(routes);
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
